<?php
/*
	本插件：$this->model('jingdong')->方法名();
	其他地方调用：model('jy_tbassistant/jingdong')->方法名();
*/
namespace jy_tbassistant;
defined('BY_JYA') or exit('error');
class jingdong extends \plugin{
	/**
     * 京东采集
     */
	public function get_item_jingdong($itemid = '', $jingdongurl = '', $cates = '', $merchid = 0)
	{
		error_reporting(0);
		$goodsid=pdo_getcolumn('jy_tbassistant_catch',array('catch_source' => 'jingdong', 'catch_id' => $itemid),'goodsid');
		$g = pdo_get('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'id'=>$goodsid));
		$item = array();
		$item['id'] = $g['id'];
		$item['merchid'] = $merchid;
		if (!(empty($merchid))) {
			$item['nochecked'] = 1;
		}
		$pcates = array();
		$ccates = array();
		$tcates = array();
		$pcateid = 0;
		$ccateid = 0;
		$tcateid = 0;
		if (is_array($cates)) 
		{
			foreach ($cates as $key => $cid ) 
			{
				$c = pdo_get('jy_weishop_goods_group',array('id' => $cid, 'uniacid' => $_SESSION['uniacid']),'parentid');
				if ($c['parentid'] == 0) {
					$pcates[] = $cid;
				}else{
					$ccates[] = $cid;
				}
				if ($key == 0) 
				{
					if ($c['parentid'] == 0) 
					{
						$pcateid = $cid;
					}else {
						$crow = pdo_get('jy_weishop_goods_group',array('id' => $cid, 'uniacid' => $_SESSION['uniacid']),'parentid');
						$pcateid = $crow['parentid'];
						$ccateid = $cid;
					}
				}
			}
		}
		$item['pcate'] = $pcateid;
		$item['ccate'] = $ccateid;
		$item['tcate'] = $tcateid;
		if (!(empty($cates))) 
		{
			$item['cates'] = implode(',', $cates);
		}
		$item['pcates'] = implode(',', $pcates);
		$item['ccates'] = implode(',', $ccates);
		$item['tcates'] = implode(',', $tcates);
		$item['itemid'] = $itemid;
		$item['total'] = 10;
		$item['sales'] = 0;
		$priceurl = $this->get_jingdong_price_url($itemid);
		$responsePrice = cfc('http')->ihttp_get($priceurl);
		$contentePrice = $responsePrice['content'];

		if (empty($contentePrice)) {
			return array('result' => '0', 'error' => '未从京东获取到商品信息!');
		}

		$price = json_decode($contentePrice, true);
		$item['marketprice'] = $price[0]['p'];
		$url = $this->get_jingdong_detail_url($itemid);
		$responseDetail = cfc('http')->ihttp_get($url);
		$contenteDetail = $responseDetail['content'];
		$details = json_decode($contenteDetail, true);
		$item['title'] = $details['ware']['wname'];
		$pics = array();
		$imgurls = $details['ware']['images'];

		foreach ($imgurls as $imgurl) {
			if (count($pics) < 4) {
				if (count($pics) == 0) {
					$iurl = $imgurl['bigpath'];

					if (stripos($iurl, '//') == 0) {
						$iurl .= 'http:' . $iurl;
					}

					$pics[] = $iurl;
				}
				else {
					$iurl = $imgurl['bigpath'];

					if (stripos($iurl, '//') == 0) {
						$iurl .= 'http:' . $iurl;
					}

					$pics[] = $iurl;
				}
			}
		}

		$item['pics'] = $pics;
		$specs = array();
		$prodectContent = $details['wdis'];
		$prodectContent = strval($prodectContent);
		$prodectContent = $this->model('model')->contentpasswh($prodectContent);
		$item['content'] = $prodectContent;
		$params = array();
		$pr = $details['ware']['wi']['code'];
		$pr = json_decode($pr, 1);

		foreach ($pr as $value) {
			foreach ($value as $key => $val) {
				if (is_array($val)) {
					$paramsValue = '';

					foreach ($val as $v) {
						foreach ($v as $k1 => $v1) {
							if (!empty($v1)) {
								$params[] = array('title' => $k1, 'value' => $v1);
							}
						}
					}
				}
				else {
					if (!empty($val)) {
						$params[] = array('title' => $key, 'value' => $val);
					}
				}
			}
		}

		$item['params'] = $params;
		return $this->save_jingdong_goods($item, $jingdongurl);
	}

	/**
     * 京东全球购抓取
     * @params 与京东助手相同
     * @author cunxin
     */
	public function get_item_jdHK($itemid = '', $jingdongurl = '', $cates = '', $merchid = 0)
	{
		error_reporting(0);
		$goodsid=pdo_getcolumn('jy_tbassistant_catch',array('catch_source' => 'jingdong', 'catch_id' => $itemid),'goodsid');
		$g = pdo_get('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'id'=>$goodsid));
		$url = 'http://item.jd.hk/' . $itemid . '.html';
		$response = cfc('http')->ihttp_get($url);
		$length = strval($response['headers']['Content-Length']);

		if (empty($length)) {
			return array('result' => '0', 'error' => '未从京东获取到商品信息!');
		}

		$content = iconv('GBK', 'UTF-8', $response['content']);
		preg_match('/<div class="sku-name">\\n{1}[\\s\\S\\n]*<\\/span>\\n(.+)<\\/div>\\n\\s*<div class="news">/', $content, $prodectName);
		$prodectName = trim($prodectName[1]);

		if ($prodectName == NULL) {
			return array('result' => '0', 'error' => '宝贝不存在!');
		}

		$item = array();
		$item['id'] = $g['id'];
		$item['merchid'] = $merchid;

		if (!empty($merchid)) {
			if (empty($_W['merch_user']['goodschecked'])) {
				$item['checked'] = 1;
			}
			else {
				$item['checked'] = 0;
			}
		}

		$pcates = array();
		$ccates = array();
		$tcates = array();
		$pcateid = 0;
		$ccateid = 0;
		$tcateid = 0;
		if (is_array($cates)) 
		{
			foreach ($cates as $key => $cid ) 
			{
				$c = pdo_get('jy_weishop_goods_group',array('id' => $cid, 'uniacid' => $_SESSION['uniacid']),'parentid');
				if ($c['parentid'] == 0) {
					$pcates[] = $cid;
				}else{
					$ccates[] = $cid;
				}
				if ($key == 0) 
				{
					if ($c['parentid'] == 0) 
					{
						$pcateid = $cid;
					}else {
						$crow = pdo_get('jy_weishop_goods_group',array('id' => $cid, 'uniacid' => $_SESSION['uniacid']),'parentid');
						$pcateid = $crow['parentid'];
						$ccateid = $cid;
					}
				}
			}
		}
		$item['pcate'] = $pcateid;
		$item['ccate'] = $ccateid;
		$item['tcate'] = $tcateid;
		if (!(empty($cates))) 
		{
			$item['cates'] = implode(',', $cates);
		}
		$item['pcates'] = implode(',', $pcates);
		$item['ccates'] = implode(',', $ccates);
		$item['tcates'] = implode(',', $tcates);
		$item['itemid'] = $itemid;
		$item['title'] = $prodectName;
		$pics = array();
		preg_match_all('/<img.+src=\'(.+)\' data-url.+data-img=\'1\' width=\'75\' height=\'75\'>/', $content, $picRet);

		if (empty($picRet[1])) {
			return array('result' => '0', 'error' => '不能抓取到图片');
		}

		foreach ($picRet[1] as $pic) {
			$pics[] = 'https:' . str_replace('s75x75', 's450x450', $pic);
		}

		$item['pics'] = $pics;
		$specs = array();
		$item['total'] = 10;
		$item['sales'] = 0;
		$priceContent = cfc('http')->ihttp_get('https://p.3.cn/prices/mgets?skuIds=J_' . $itemid);
		$prodectPrices = json_decode($priceContent['content'], 1);
		$item['marketprice'] = $prodectPrices[0]['p'];
		$url = $this->get_jingdong_detail_url($itemid);
		$responseDetail = cfc('http')->ihttp_get($url);
		$contenteDetail = $responseDetail['content'];
		$details = json_decode($contenteDetail, true);
		$prodectContent = $details['wdis'];
		$prodectContent = strval($prodectContent);
		$prodectContent = $this->model('model')->contentpasswh($prodectContent);
		$item['content'] = $prodectContent;
		$params = array();
		$pr = $details['ware']['wi']['code'];
		preg_match_all('/<td class="tdTitle">(.*?)<\\/td>/i', $pr, $params1);
		preg_match_all('/<td>(.*?)<\\/td>/i', $pr, $params2);
		$paramsTitle = $params1[1];
		$paramsValue = $params2[1];

		if (count($paramsTitle) == count($paramsValue)) {
			$i = 0;

			while ($i < count($paramsTitle)) {
				$params[] = array('title' => $paramsTitle[$i], 'value' => $paramsValue[$i]);
				++$i;
			}
		}

		$item['params'] = $params;
		return $this->save_jingdong_goods($item, $jingdongurl);
	}
	public function save_jingdong_goods($item = array(), $catch_url = '')
	{
		$params=array('uniacid'=>$_SESSION['uniacid'],'catch_source' => 'jingdong', 'catch_id' => $item['itemid'], 'catch_url' => $catch_url);
		$data = array(
			'uniacid' => $_SESSION['uniacid'],
			'param'=>ijson_encode($item['params']),
			'title' => $item['title'],
			'subtitle' => $item['subTitle'],
			'merchid' => $item['merchid'],
			'checked' => $item['checked'],
			'total' => $item['total']?:18,
			'price' => $item['marketprice'],
			'minprice' => $item['marketprice'],
			'maxprice' => $item['marketprice'],
			'costprice' => $item['productPrice'],
			'pcate' => $item['pcate'],
			'ccate' => $item['ccate'],
			'tcate' => $item['tcate'],
			'cates' => $item['cates'],
			'salenum' => $item['sales'],
			'createtime' => time(),
			'updatetime' => time(),
			'isoption' => (0 < count($item['options']) ? 1 : 0),
			'status' => 0,
			'buylevels' => '',
			'showlevels' => '',
			'buygroups' => '',
			'showgroups' => '',
			'storeids' => ''
		);
		if(!$item['title']){
			exi('采集失败，由于京东防盗链规则改变，现无法采集！','error');
		}
		if (empty($item['merchid'])) {
			//$data['discounts'] = '{"type":"0","default":"","default_pay":""}';
		}

		$thumb_url = array();
		$pics = $item['pics'];
		$piclen = count($pics);

		if (0 < $piclen) {
			$img=cfc('files')->source_save($pics[0],'image','jpg','商品单图','',0);
			if (empty($img)) {
				$img = $pics[0];
			}

			$data['thumb'] = $img;

			if (1 < $piclen) {
				$i = 1;

				while ($i < $piclen) {
					$img = cfc('files')->source_save($pics[$i],'image','jpg','商品单图','',0);

					if (empty($img)) {
						$img = $pics[$i];
					}

					$thumb_url[] = $img;
					++$i;
				}
			}
		}
		$data['images'] = serialize($thumb_url);
		$gid=pdo_getcolumn('jy_tbassistant_catch',array('catch_source' => 'jingdong', 'catch_id' => $item['itemid']),'goodsid');
		$goods = pdo_get('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$gid));

		if (empty($goods)) {
			pdo_insert('jy_weishop_goods', $data);
			$goodsid = pdo_insertid();
			$params['goodsid']=$goodsid;
			pdo_insert('jy_tbassistant_catch', $params);
		}
		else {
			$goodsid = $goods['id'];
			unset($data['createtime']);
			pdo_update('jy_weishop_goods', $data, array('id' => $goodsid));
		}
		$goods_params = pdo_getall('jy_weishop_goods_option',array('goodsid' => $goodsid));
		$params = $item['params'];
		$paramids = array();
		$displayorder = 0;

		/*foreach ($params as $p) {
			$oldp = pdo_fetch('select * from ' . tablename('jy_weishop_goods_option') . ' where goodsid=:goodsid and title=:title limit 1', array(':goodsid' => $goodsid, ':title' => $p['title']));
			$paramid = 0;
			$d = array('uniacid' => $_W['uniacid'], 'goodsid' => $goodsid, 'title' => $p['title'], 'value' => $p['value'], 'displayorder' => $displayorder);

			if (empty($oldp)) {
				pdo_insert('jy_weishop_goods_option', $d);
				$paramid = pdo_insertid();
			}
			else {
				pdo_update('jy_weishop_goods_option', $d, array('id' => $oldp['id']));
				$paramid = $oldp['id'];
			}

			$paramids[] = $paramid;
			++$displayorder;
		}*/

		if (0 < count($paramids)) {
			pdo_delete('jy_weishop_goods_option', array('goodsid' => $goodsid,'id <>'=>implode(',', $paramids)));
		}else {
			pdo_delete('jy_weishop_goods_option',array('goodsid' => $goodsid));
		}

		$content = $item['content'];
		preg_match_all('/<img.*?src=[\\\\\'| \\"](.*?(?:[\\.gif|\\.jpg]?))[\\\\\'|\\"].*?[\\/]?>/', $content, $imgs);

		if (isset($imgs[1])) {
			foreach ($imgs[1] as $img) {
				$catchimg = $img;

				if (substr($catchimg, 0, 2) == '//') {
					$img = 'http://' . substr($img, 2);
				}

				$im = array('catchimg' => $catchimg, 'system' => cfc('files')->source_save($img,'image','','','',0));
				$images[] = $im;
			}
		}

		$html = $content;

		if (isset($images)) {
			foreach ($images as $img) {
				if (!empty($img['system'])) {
					$html = str_replace($img['catchimg'], $img['system'], $html);
				}
			}
		}

		$html = $this->model('model')->html_to_images($html);
		$d = array('content' => $html);
		pdo_update('jy_weishop_goods', $d, array('id' => $goodsid));
		return array('result' => '1', 'goodsid' => $goodsid);
	}
	public function get_jingdong_info_url($itemid)
	{
		$url = 'http://item.m.jd.com/ware/view.action?wareId=' . $itemid;
		$url = $this->model('model')->getRealURL($url);
		return $url;
	}

	public function get_jingdong_detail_url($itemid)
	{
		$url = 'http://item.m.jd.com/ware/detail.json?wareId=' . $itemid;
		$url = $this->model('model')->getRealURL($url);
		return $url;
	}

	public function get_jingdong_price_url($itemid)
	{
		$url = 'https://pe.3.cn/prices/mgets?skuids=' . $itemid;
		$url = $this->model('model')->getRealURL($url);
		return $url;
	}
}
?>